package com.jstyle.jclifexd.activity;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.app.MyApplication;
import com.jstyle.jclifexd.minterface.DialogDataListener;
import com.jstyle.jclifexd.model.ActionData;
import com.jstyle.jclifexd.model.NetResultData;
import com.jstyle.jclifexd.model.UserInfo;
import com.jstyle.jclifexd.utils.NetWorkConast;
import com.jstyle.jclifexd.utils.RxBus;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.SharedPreferenceUtils;
import com.jstyle.jclifexd.utils.Utils;
import com.jstyle.jclifexd.view.EditTextWithDelete;
import com.jstyle.jclifexd.view.FeedBackDialog;
import com.jstyle.jclifexd.view.FeedBackFinishDialog;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/8/10.
 */

public class FeedBackActivity extends BaseActivity implements DialogDataListener {

    @BindView(R.id.bt_feed_back)
    ImageView btFeedBack;
    @BindView(R.id.et_advice_text)
    EditTextWithDelete etAdviceText;
    @BindView(R.id.et_advice_email)
    EditTextWithDelete etAdviceEmail;
    @BindView(R.id.bt_advice)
    Button btAdvice;
    @BindView(R.id.switch_log)
    SwitchCompat switchLog;
    @BindView(R.id.et_advice_name)
    EditTextWithDelete etAdviceName;
    @BindView(R.id.bt_feedback_topic)
    EditTextWithDelete btFeedbackTopic;
    private static final String KEY_Log_Switch = "Log_Switch";
    @BindView(R.id.bt_title)
    Button btTitle;
    @BindView(R.id.ScrollView)
    android.widget.ScrollView ScrollView;
    private FeedBackDialog feedBackDialog;
    @BindArray(R.array.array_topic)
    String[] topicArray;
    private String topic;
    private Disposable subscription;
    private static final int feedback = 60;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advice);
        ButterKnife.bind(this);

        init();
    }

    private void init() {
        ScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (getCurrentFocus() != null
                            && getCurrentFocus().getWindowToken() != null) {
                        manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                return false;
            }
        });
        UserInfo userInfo = NetWorkUtil.getUser();
        if (userInfo != null) {
            String name = userInfo.getName();
            String phone = userInfo.getPhone();
            if (!TextUtils.isEmpty(name)) etAdviceName.setText(name);
            if (!TextUtils.isEmpty(phone) && phone.contains("@")) etAdviceEmail.setText(phone);
        }
        ScreenUtils.setTitleTypeface(btTitle);
        subscription = RxBus.getInstance().toObservable(ActionData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<ActionData>() {
            @Override
            public void accept(ActionData data) throws Exception {
                String action = data.getAction();
                if (ActionData.FinishFeedBack.equals(action)) {
                    finish();
                }
            }
        });
        boolean logSwitch = SharedPreferenceUtils.getBoolean(KEY_Log_Switch, true);
        switchLog.setChecked(logSwitch);
        switchLog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferenceUtils.setSpBoolean(KEY_Log_Switch, isChecked);

            }
        });

    }

    @OnClick({R.id.bt_feed_back, R.id.bt_advice, R.id.bt_feedback_topic})
    public void onViewClicked(View view) {
        if(Utils.isFastClick()){return;}
        switch (view.getId()) {
            case R.id.bt_feed_back:
                finish();
                break;
            case R.id.bt_advice:
                submitAdvice();
                break;
            case R.id.bt_feedback_topic:
                 Intent intent=new Intent(this,FeedbackListActivity.class);
                 startActivityForResult(intent,feedback);
                  showTopicDialog();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == feedback && resultCode == RESULT_OK) {
            String info = data.getStringExtra(FeedbackListActivity.InFo);
            if (!TextUtils.isEmpty(info)) btFeedbackTopic.setText(info);
        }
    }

    private void showTopicDialog() {
        if (feedBackDialog == null) {
            feedBackDialog = new FeedBackDialog(this, R.style.jstyleDialog_style);
            feedBackDialog.setDialogDataListener(this);

        }
        feedBackDialog.show();
    }

    public static boolean checkEmail(String email) {
        String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        return Pattern.matches(regex, email);
    }

    private void submitAdvice() {
        if (!NetWorkUtil.isNetworkConnected(this)) {
            showToast(getString(R.string.Network_not_availa));
            return;
        }
        // TODO Auto-generated method stub
        final String adviceText = etAdviceText.getText().toString();
        final String email = etAdviceEmail.getText().toString();
        String name = etAdviceName.getText().toString();
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(adviceText)) {
            Toast.makeText(this,
                    getResources().getString(R.string.fill_all_info),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (!checkEmail(email)) {
            showToast(getString(R.string.email_format_wrong));
            return;
        }
        etAdviceText.setText("");
        String otherAdvice = btFeedbackTopic.getText().toString();
        if (TextUtils.isEmpty(otherAdvice)) otherAdvice = ".";
        Map<String, String> feedBackMap = new HashMap<>();
        feedBackMap.put(NetWorkConast.KEY_token, "");
        feedBackMap.put(NetWorkConast.KEY_email, email);
        feedBackMap.put(NetWorkConast.KEY_Content, adviceText);
        feedBackMap.put(NetWorkConast.KEY_devicetype, MyApplication.getJstyleDevice().getDeviceNo());
        feedBackMap.put(NetWorkConast.KEY_AppName, getString(R.string.app_name));
        feedBackMap.put(NetWorkConast.KEY_osType, "Android");
        feedBackMap.put(NetWorkConast.KEY_Feedback_Name, name);
        feedBackMap.put(NetWorkConast.KEY_Feedback_Topic, otherAdvice);
        feedBackMap.put(NetWorkConast.KEY_AppVersion, getAppVersion());
        NetWorkUtil.getInstance().getJstyleApi().feedBack(feedBackMap).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
                                                                                                                      @Override
                                                                                                                      public void accept(Disposable disposable) throws Exception {
                                                                                                                          showProgressDialog(getString(R.string.Submitting));
                                                                                                                      }
                                                                                                                  }

        ).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<NetResultData>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NetResultData value) {
                disMissProgressDialog();
                int resultCode = value.getMsgCode();
                String message = "";
                if (resultCode == 1) {
                    showFeedBackFinishDialog();
//                    message = getString(R.string.feedback_successful);

                } else if (resultCode == 1221) {
                    message = getString(R.string.email_format_wrong);
                    showToast(message);
                }

            }

            @Override
            public void onError(Throwable e) {
                disMissProgressDialog();
                showToast(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });

    }

    private void showFeedBackFinishDialog() {
        new FeedBackFinishDialog(this, R.style.jstyleDialog_style).show();
    }


    public String getAppVersion() {
        PackageInfo packageInfo;
        String versionName = "";
        try {
            packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            versionName = packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;

    }


    @Override
    public void dataListener(String data) {

    }


    int topicPosition;

    @Override
    public void dataListener(int position) {
        topicPosition = position;
        btFeedbackTopic.setText(topicArray[topicPosition]);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSubscribe(subscription);
    }
}
